<?php

namespace App\Http\Middleware;

use App\Consts\GlobalLoginConst;
use App\Consts\GlobalUserConst;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use Closure;
use Illuminate\Http\Request;

class GetLoginUser
{
    /**
     * Handle an incoming request.
     * 获取当前登录用户信息
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->cookie('token') ?: $request->header('token');

        // 没有token
        if (!$token) {
            return $next($request->merge([
                GlobalLoginConst::LOGIN_STATE_INFO_USER => null,
                GlobalLoginConst::LOGIN_STATE_INFO_TOKEN => '',
            ]));
        }

        // 根据令牌可以找到用户
        $cacheUser = Cache::getInstance([
            'platform' => GlobalLoginConst::LOGIN_PLATFORM_WEB_STR,
            'token' => $token,
        ])->get(CacheKey::USER_LOGIN_STATUS);
        $user = service()->UserService->getUserByAccessToken($token);
        if (!$cacheUser || !$user) {
            // 去缓存查询，如果查到说明当前用户是：1.游客，2.第三方登录后没有绑定手机号的用户（特殊的游客）
            $cacheTourist = Cache::getInstance([
                'token' => $token,
            ])->hGetAll(CacheKey::OAUTH_TOURIST);
            $cacheTourist['identity'] = GlobalUserConst::IDENTITY_TOURIST;
            $user = $cacheTourist ? (object)$cacheTourist : null;
        }

        return $next($request->merge([
            GlobalLoginConst::LOGIN_STATE_INFO_USER => $user,
            GlobalLoginConst::LOGIN_STATE_INFO_TOKEN => $token,
        ]));
    }
}
